<template>
  <div class="dept-projet">
    <!--组织结构-->
    <div class="dept-projet-head" @click="showDialog">
      <div class="select-project">
        <div class="icon-name">
          <i class="el-icon-loading location-icon" v-if="projectLoading"></i>
          <svg-icon icon-class="location" class="location-icon" v-else />
          <span class="dept-projet-ellipsis" style="margin-left: 10px;">{{ selectProjectName }}</span>
        </div>
        <i class="el-icon-arrow-down" style="color: #c4dbe6" />
      </div>
    </div>

    <el-dialog
      title="选择项目"
      width="500px"
      :visible.sync="dialogVisible"
      append-to-body
      :close-on-click-modal="false"
    >
      <div class="aside-tree-container">
        <div>
          <el-input
            v-model="deptName"
            placeholder="请输入部门/项目名称 → 回车检索"
            clearable
            size="mini"
            prefix-icon="el-icon-search"
            style="margin-bottom: 12px;width: 240px;margin-left: 20px;margin-right: 10px"
            @keyup.enter.native="searchProject"
          />
          <el-button type="primary" size="mini" icon="el-icon-search" @click="searchProject">搜索</el-button>
        </div>
        <el-scrollbar style="height: calc(70vh - 90px);font-size: 12px;">
          <el-tree
            ref="tree"
            node-key="id"
            :data="deptOptions"
            :props="defaultProps"
            accordion
            highlight-current
            :expand-on-click-node="false"
            :filter-node-method="filterNodeDept"
            :default-expanded-keys="expandKeys"
            @node-click="handleNodeClickDept"
          >
            <div slot-scope="{ node }">
              <svg-icon
                class="preview-icon"
                style="color: #416ca6;"
                icon-class="druid"
              />
              <span style="padding-left: 6px;">{{ node.label }}</span>
            </div>
          </el-tree>
        </el-scrollbar>
      </div>
      <div class="select-project-btn">
        <el-button type="primary" @click="submitProject">确 定</el-button>
      </div>
    </el-dialog>
    <!--楼栋数据-->
    <div v-if="level != 'project'" class="project-content">
      <div class="aside-tree-container">
        <el-scrollbar class="aside-scrollbar">
          <el-tree
            ref="treeProjectRef"
            v-loading="projectLoading"
            :node-key="nodeKey"
            size="mini"
            :data="buildings"
            :props="defaultProProps"
            highlight-current
            :expand-on-click-node="false"
            :filter-node-method="filterNodePro"
            default-expand-all
            @node-click="handleNodeClickPro"
          >
            <div slot-scope="{ node, data }">
              <svg-icon v-if="data.type === 'dept'" icon-class="ico_area" class="preview-icon" />
              <svg-icon
                v-else-if="data.type === 'project'"
                class="preview-icon"
                style="color: #416ca6;"
                icon-class="druid"
              />
              <span v-else-if="data.type === 'building' && data.buildingType" class="font-bg"> {{ data.buildingType | buildingTypeFilter }} </span>
              <svg-icon
                v-else-if="data.type === 'building'"
                class="preview-icon"
                icon-class="ico_city"
                @click.stop="plateProjectDevices(data)"
              />
              <span class="tree-label">{{ node.label }}</span>
            </div>
          </el-tree>
        </el-scrollbar>
      </div>
    </div>
  </div>
</template>

<script>
import { buildingList, getAuthCurProject } from '@/api/common'
import { treeBuildingManage } from '@/api/baseManage/buildingManage'
export default {
  name: 'AuthProject',
  props: {
    level: { // 展示、返回数据层次 building: 楼栋，unit: 单元 project： 项目
      type: String,
      default: () => 'building'
    },
    type: { // 0: 项目前期名 1：项目后期名称
      type: Number,
      default: () => 1
    }
  },
  data() {
    return {
      deptName: '',
      projectLoading: false,
      deptOptions: [],
      buildings: [],
      defaultProps: {
        children: 'children',
        label: 'cflastname'
      },
      defaultProProps: {
        children: 'children',
        label: 'name'
      },
      expandKeys: [], // 组织项目
      selectProject: {}, // 选择的项目对象
      selectProjectName: '',
      dialogVisible: false,
      nodeKey: 'id',
      currentProjet: {},
      projectMsg: {}
    }
  },
  watch: {
    // 根据名称筛选项目树
  },
  created() { // 初始化
    // this.currentProjet = JSON.parse(localStorage.getItem('currentProject'))
    this.getTreeselect()
    this.$eventBus.$on('unitUpdate', () => {
      this.getBuildingsByPro(this.selectProject.id)
    })
  },
  beforeDestroy() {
    // 关闭监听事件
    this.$eventBus.$off('unitUpdate')
  },
  methods: {
    // 检索
    searchProject() {
      this.$refs.tree.filter(this.deptName)
    },
    /** 查询部门与项目下拉树结构 */
    getTreeselect() {
      this.projectLoading = true
      getAuthCurProject().then((response) => {
        this.projectLoading = false
        this.deptOptions = response.data
        if (response.data && response.data.length) {
          var storgeProject = JSON.parse(localStorage.getItem('currentProject'))  || {}
          for (var i = 0; i < response.data.length; i++) {
            if (storgeProject['id'] === response.data[i].fid) {
              this.currentProjet = response.data[i]
              this.selectProject = { ...this.currentProjet }
              this.selectProjectName = this.selectProject.cflastname
              this.projectMsg = {
                'id': this.selectProject.fid,
                'lastname': this.selectProject.cflastname,
                'leaf': true,
                'name': this.selectProject.cflastname,
                'parentId': this.selectProject.fparentid,
                'type': 'project'
              }
              this.getBuildingsByPro(this.selectProject.fid)
              return
            }
          }
          this.currentProjet = response.data[0]
          this.selectProject = { ...this.currentProjet }
          this.selectProjectName = this.selectProject.cflastname
          this.projectMsg = {
            'id': this.selectProject.fid,
            'lastname': this.selectProject.cflastname,
            'leaf': true,
            'name': this.selectProject.cflastname,
            'parentId': this.selectProject.fparentid,
            'type': 'project'
          }
          this.getBuildingsByPro(this.selectProject.fid)
          return
        }
      })
    },
    /** 根据项目ID获取楼栋 */
    getBuildingsByPro(projectId) {
      if (!projectId) return
      if (this.level === 'project') {
        this.$emit('selectProject', { ...this.projectMsg })
      }
      if (this.level === 'building') {
        this.defaultProProps.label = 'name'
        this.getBuildingList(projectId)
      } else if (this.level === 'unit') {
        this.defaultProProps.label = 'fnameL2'
        this.getBuildingTree(projectId)
      }
    },
    // 根据项目ID获取楼栋+单元树列表
    getBuildingTree(projectId) {
      // projectId = '14BhQdVOSwyOLB45K3wGb/nl6Ss=' // 测试使用
      this.projectLoading = true
      treeBuildingManage({ cfcurprojectid: projectId }).then((response) => {
        this.buildings = response.data
        this.projectLoading = false
        if (response.data.length > 0) {
          this.$nextTick(() => {
            this.$refs.treeProjectRef.setCurrentKey(response.data[0].fid)
          })
          // 楼栋下挂载类型：单元或房屋
          let childType = null
          if (response.data[0].children.length > 0) {
            childType = 'unit'
          }
          this.$emit('selectBuilding', { ...response.data[0], childType, project: this.selectProject })
        } else {
          this.$emit('selectBuilding', { project: this.selectProject })
        }
      })
    },
    // 根据项目ID获取楼栋列表
    getBuildingList(projectId) {
      this.projectLoading = true
      buildingList({ projectId }).then((response) => {
        this.buildings = response.data
        this.projectLoading = false
        if (response.data.length > 0) {
          this.$nextTick(() => {
            this.$refs.treeProjectRef.setCurrentKey(response.data[0].id)
          })
          this.$emit('selectBuilding', { ...response.data[0], project: this.selectProject })
        } else {
          this.$emit('selectBuilding', { project: this.selectProject })
        }
      })
    },
    // 组织筛选节点
    filterNodeDept(value, data, node) {
      if (!value) return true
      // return data.label.indexOf(value) !== -1
      let parentNode = node.parent
      let labels = [node.label]
      let level = 1
      while (level < node.level) {
        labels = [...labels, parentNode.label]
        parentNode = parentNode.parent
        level++
      }
      return labels.some(label => label && label.indexOf(value) !== -1)
    },
    // 组织的项目节点节点单击事件
    handleNodeClickDept(data, node) {
      console.log(data)
      this.selectProject = data
    },
    showDialog() {
      this.dialogVisible = true
      this.$nextTick(() => {
        this.$refs.tree.setCurrentKey(this.selectProject.id)
      })
    },
    submitProject() {
      this.dialogVisible = false
      this.selectProjectName = this.selectProject.cflastname
      this.projectMsg = {
        'id': this.selectProject.fid,
        'lastname': this.selectProject.cflastname,
        'leaf': true,
        'name': this.selectProject.cflastname,
        'parentId': this.selectProject.fparentid,
        'type': 'project'
      }
      localStorage.setItem('currentProject', JSON.stringify(this.projectMsg))
      this.getBuildingsByPro(this.selectProject.fid)
    },
    // 项目筛选节点
    filterNodePro(value, data, node) {
      if (!value) return true
      // return data.name.indexOf(value) !== -1
      let parentNode = node.parent
      let labels = [node.label]
      let level = 1
      while (level < node.level) {
        labels = [...labels, parentNode.label]
        parentNode = parentNode.parent
        level++
      }
      return labels.some(label => label && label.indexOf(value) !== -1)
    },
    // 项目节点单击事件
    handleNodeClickPro(data, node) {
      console.log(data, node)
      if (data.type === 'building') {
        // 楼栋下挂载类型：单元或房屋
        let childType = null
        if (data.children && data.children.length > 0) {
          childType = 'unit'
        }
        this.$emit('selectBuilding', { ...data, childType, project: this.selectProject })
      } else if (data.type === 'unit') {
        this.$emit('selectUnit', { ...data, building: node.parent.data })
      }
    }
  }
}
</script>

<style scoped lang='scss'>
  .dept-projet {
    font-size: 12px;
    box-shadow: 0 0 2px 0 rgba(0, 0, 0, 0.2);
    .dept-projet-head {
      border-bottom: 1px solid rgba(0, 0, 0, 0.1);
      .select-project {
        height: 40px;
        line-height: 40px;
        display: flex;
        font-size: 14px;
        padding: 0 20px;
        justify-content: space-between;
        align-items: center;
        background-color: #ecf5ff;
        color: #606266;
        cursor: pointer;
        .icon-name {
          width: 100%;
          line-height: 40px;
          height: 40px;
          display: flex;
          align-items: center;
        }
        .location-icon {
          font-size: 16px;
          color: #409EFF;
        }
        .dept-projet-ellipsis {
          display: inline-block;
          width: calc(100% - 30px);
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
        }
      }
    }
    .project-content {
      margin-top: 10px;
      padding-left: 10px;
      .project-search {
        padding-right: 10px;
      }
    }
    .aside-scrollbar {
      height: calc(100vh - 170px);
    }
    .preview-icon {}
    .tree-label {
      padding-left: 6px;
    }
  }
  .select-project-btn {
    padding: 20px 30px 0 0;
    display: flex;
    justify-content: flex-end;
  }
  .font-bg {
    background-color: rgba(26,179,148, .6);
    color: white;
    border-radius: 50%;
    display: inline-block;
    height: 20px;
    line-height: 20px;
    padding: 0 3px;
  }
</style>
<style lang="scss">
  .check-type-scrollbar-container,
  .aside-tree-container {
    .el-scrollbar .el-scrollbar__wrap {
      overflow-x: hidden;
    }
  }
</style>
